require('../js/global.js');
var Iconv = require('iconv').Iconv;
var csv = require('../js/csv.js');
var ServerManager = require('../js/servers.js').ServerManager;

var utf8Converter = new Iconv('GBK', 'UTF8');
var gbkConverter = new Iconv('UTF8', 'GBK');

var repositoryPath = config.system.home + '/git/ssanguo';
var globalServerConfName = 'globalserver.dat';
var defaultGlobalServerConfPath = util.format('%s/conf/%s', repositoryPath, globalServerConfName);
var defaultGlobalServerConf = new csv.GlobalCSV(defaultGlobalServerConfPath);
var globalServerHead = utf8Converter.convert(fs.readFileSync(defaultGlobalServerConfPath)).toString().split('\n').splice(0,2).join('\n');


var argv = process.argv;
var gameSid = 0;
if (argv.length > 2) {
    gameSid = parseInt(argv[2]);
}

var serverManager = new ServerManager();
serverManager.loadGame(function(err) {
    if (err) {
        console.log(util.format('load failed: %j', err));
        process.exit(1);
    }

    generateGlobalServer();
    process.exit();
});


function generateGlobalServer() {
    if (gameSid) {
        var server = serverManager.gameServers[gameSid];
        if (server) {
            saveGlobalServerConf(server, getGlobalServerConf(server));
        }
    } else {
        for (var sid in serverManager.gameServers) {
            var server = serverManager.gameServers[sid];
            if (server.isValid()) {
                saveGlobalServerConf(server, getGlobalServerConf(server));
            }
        }
    }
}

function getGlobalServerConf(server) {
    var sid = server.id;

    var conf = {};
    for (var key in defaultGlobalServerConf) {
        conf[key] = null;
    }
    conf.PlatformName = config.platform.name;
    conf.GamexURL = defaultGlobalServerConf.GamexURL;

    conf.ServerStartTime = Date.createFromStamp(server.stamp).format('yyyy:MM:dd:hh:mm:ss');
    conf.FirstLeagueWarTime = Date.createFromStamp(server.leagueWarTime).format('yyyy:MM:dd:hh:mm:ss');

    // 系统奖励配置
    var systemReward = config.runtime.getSystemReward(sid);
    conf.SystemRewardId = systemReward.id;
    conf.SystemRewardTime = systemReward.time;

    // 跨服充值排行榜服务器开启时间限制
    conf.ServerPayRankServerTime = config.runtime.ServerPayRankServerTime;

    // 云服配置 
    var cloudSid = config.game.cloud_sid(sid);
    var cloudHostIP = config.server.query('cloud', cloudSid, 'ip');
    conf.CloudHost = cloudHostIP;
    conf.CloudPort = config.cloud.port(cloudSid);

    // 跨服排行配置
    var cloudRankSid = config.game.cloud_rank_sid(sid);
    var cloudRankHostIP = config.server.query('cloud_rank', cloudRankSid, 'ip');
    conf.CloudRankHost = cloudRankHostIP;
    conf.CloudRankPort = config.cloud_rank.port(cloudRankSid);

    // 跨服金矿配置
    var cloudMineSid = config.game.cloud_mine_sid(sid);
    var cloudMineHostIP = config.server.query('cloud_mine', cloudMineSid, 'ip');
    conf.ServerMineHost = cloudMineHostIP;
    conf.ServerMinePort = config.cloud_mine.port(cloudMineSid);

    // 决战天下配置
    var cloudBattleSid = config.game.cloud_battle_sid(sid);
    var cloudBattleIP = config.server.query('cloud_battle', cloudBattleSid, 'ip');
    if (cloudBattleIP) {
        conf.BattleWorldHost = cloudBattleIP;
        conf.BattleWorldPort = config.cloud_battle.port(cloudBattleSid);
    }
    conf.FirstBattleWorldTime = config.runtime.gameFirstCloudBattleTime(sid);

    //王者战场配置
    var champsbattleSid = config.game.champsbattle_sid(sid);
    if (champsbattleSid) {
        conf.ChampsBattleHost = config.server.query('champsbattle', champsbattleSid, 'ip');
        conf.ChampsBattlePort = config.champsbattle.port(champsbattleSid);
    }

    // 群雄争霸配置
    var universeSid = config.game.universe_sid(sid);
    var universeIP = config.server.query('universe', universeSid, 'ip');
    if (universeIP) {
        conf.UniverseHost = universeIP;
        conf.UniversePort = config.universe.port(universeSid);
    }
    conf.FirstServerWarTime = config.runtime.gameFirstUniverseTime(sid);

    //跨服擂台
    var cloudArenaSid = config.game.cloudarena_sid(sid);
    if (cloudArenaSid) {
        conf.CloudArenaHost = config.server.query('cloudarena', cloudArenaSid, 'ip');
        conf.CloudArenaPort = config.cloudarena.port(cloudArenaSid);
    }

    return conf;
}

function saveGlobalServerConf(server, conf) {
    var path = util.format('%s/servers/s%d', repositoryPath, config.game.osid(server.id));
    if (!fs.existsSync(path)) {
        fs.mkdirSync(path);
    }

    var globalFile = utf8Converter.convert(fs.readFileSync(defaultGlobalServerConfPath)).toString().split('\r\n');
    var lines = [globalFile[0], globalFile[1]];
    for (var i = 2; i <= globalFile.length; ++i) {
        if (!globalFile[i]) {
            continue; 
        }

        var spliter = '\t';
        var columns = globalFile[i].split(spliter);
        columns[2] = conf[columns[1]];

        lines.push(columns.join(spliter));
    }

    fs.writeFileSync(util.format('%s/%s', path, globalServerConfName), gbkConverter.convert(lines.join('\n')));
}
